
// import NProgress from 'nprogress' // progress bar
import errorCode from '@/const/errorCode';
import router, { asyncRoutes } from '@/router/router';
import axios from 'axios';
// import { Msg } from '@/utils/resetMessage.js';
import { Toast } from 'vant-green';
import store from '@/store/main.js';
const isDev = process.env.NODE_ENV === 'development';

if (!isDev && window.location.href.indexOf('/partners') != -1){
    axios.defaults.baseURL = '/partners';
}

// import 'nprogress/nprogress.css'

let instance = axios.create();


instance.defaults.timeout = 99999999;
// 返回其他状态吗
instance.defaults.validateStatus = function (status) {
	return status >= 200 && status <= 500; // 默认的
};

instance.defaults.withCredentials = true; // 表示跨域请求时是否需要使用凭证, 默认false
instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

/*
 * NProgress Configuration
 * NProgress.configure({
 *     showSpinner: false
 * })
 */

// HTTPrequest拦截
instance.interceptors.request.use(config => {
	!config.notMask && store.commit('changeMask', 'start');
	// NProgress.start() // start progress bar
	var token = window.localStorage.getItem('access_token');
    config.headers['Access-Control-Allow-Credentials'] = true // 允许跨域携带cookie  config.headers['Access-Control-Allow-Credentials']=true
	if (token != undefined && token != '') {
		config.headers['Authorization'] = 'Bearer ' + token;
	}
	return config;
}, error => {
	return Promise.reject(error);
});


// HTTPresponse拦截
instance.interceptors.response.use(res => {
	// NProgress.done()
	store.commit('changeMask', 'end');
	const status = Number(res.status) || 200;
	const message = res.data.msg || errorCode[status] || errorCode['default'];

	if (status === 401) {
		// router.push({ path: '/login' });
        const isDev = process.env.NODE_ENV === 'development';
        this.$router.push('/notFound')
		return;
	}

	if (status !== 200) {
        Toast(message);
		if (status === 404) {
			router.push({ path: '/notFound' });
		}  /*else {
			router.push({ path: '/login' });
		}*/
		return Promise.reject(new Error(message));
	}

    // if (res.data.code == "-1") {
    //     let commonPath = '';
    //     if (window.location.href.indexOf('/partners') != -1) {
    //         commonPath = '/partners';
    //     } else {
    //         commonPath = '/strategicPartner';
    //     }
    //     location.href = commonPath + '/apps/demo/login.html';
    //     // router.push({ path: '/login' });
    // }
    return res;
}, error => {
	store.commit('changeMask', 'end');
	// NProgress.done()
	return Promise.reject(new Error(error));
});

export default instance;
